import { observable, action, toJS } from 'mobx';
import _ from 'lodash';
import CardStore from ".";
import { modeForm } from '../../util/excelUtil';
import { doSubmit } from "../../apis/card";
import { Modal, message } from "antd";
import { WeaLocaleProvider, WeaTools } from "ecCom";
import window from '../../util';
import { scrollToX, scrollTo } from './actions/doSubmit';
import $ from 'jquery';
const getLabel = WeaLocaleProvider.getLabel;
const getParent = WeaTools.WindowFunc.getParent;

export interface layoutBaseProps {
    isquickedit: string, //是否启用快速编辑
    pageexpandid: string, //编辑页面的保存扩展id
    haveVerifyRepeat: string, //0 or 1 是否有重复校验
    editLayoutid: string, //显示布局对应的编辑布局id
    verify_fields: any,   //重复验证的数据getVerifyEntity接口返回的数据
    verify_fieldinfos: any,
    haveInterface: string, //0 无接口 1 有接口
    relateField: Array<string>, //页面扩展设置了关联字段
}

export class QuickEditStore {
    card: CardStore;
    constructor(card: CardStore) {
        this.card = card;
    }
    @observable loading: boolean = false;
    @observable editFieldKey: string = '';
    @observable formItemsCurrentValue = {};
    @observable detalCurrentValue = {};
    @observable detailkeysState = {};
    @observable mainFieldState = {};
    @observable handletype: string = "";
    @observable oldValue = {};
    @observable recordParmurls = {};

    @action
    update = (params: any) => {
        for (let key in params) {
            this[key] = params[key];
        }
    }

    @action
    getEditState = (fieldkey) => {
        const { getFieldEditState } = this.card;
        const [fielid] = fieldkey.split('_');
        const { editstate } = getFieldEditState(fielid);
        return editstate;
    }

    @action
    lockEditFormItem = (fieldkey) => {
        if (!_.isEmpty(this.detalCurrentValue)) {
            return
        }
        const [fielid1, index1] = fieldkey.split('_');
        const { fieldhtmltype, isdetail, detail } = this.card.getFieldProps(fielid1); //fieldhtmltype = 6 附件
        let currentVal = modeForm.getFieldValueObj(fieldkey);
        if (fieldhtmltype == '6') {
            if (isdetail) {
                currentVal = this.card.cubeForm.$(detail).$(index1).$(fielid1).uploadData.filedatas || [];
            } else {
                currentVal = this.card.cubeForm.$(fielid1).uploadData.filedatas || [];
            }
        }
        this.oldValue = {
            ...this.oldValue,
            [fieldkey]: currentVal
        };
        const [fielid] = this.editFieldKey.split('_');
        const viewAttr = this.getEditState(this.editFieldKey);
        const _this = this;
        setTimeout(() => {
            modeForm.changeFieldAttr(_this.editFieldKey, 1);
            if (viewAttr == '3' && !this.formItemsCurrentValue[fielid]) {
                const { fieldhtmltype, } = this.card.getFieldProps(fielid);
                if (fieldhtmltype == '6') { //附件
                    modeForm.changeFieldValue(_this.editFieldKey, toJS(_this.oldValue[_this.editFieldKey]), 'upload');
                }else  if (fieldhtmltype == '3'){//浏览框
                    modeForm.changeFieldValue(_this.editFieldKey, toJS(_this.oldValue[_this.editFieldKey]));
                } else {
                    modeForm.changeFieldValue(_this.editFieldKey, {...toJS(_this.oldValue[_this.editFieldKey]),specialobj:''});
                }
            }
            _this.editFieldKey = fieldkey;
            // if(_.isEmpty(_this.mainFieldState)){
            //     _this.setFormItemsCurrentValue({});
            // }
            modeForm.changeFieldAttr(fieldkey, _this.getEditState(fieldkey));
        }, 300)

    }

    @action
    setFormItemsCurrentValue = formItemsCurrentValue => {
        this.formItemsCurrentValue = formItemsCurrentValue;
    }

    @action
    handleClickOutSide = (e) => {
        if (this.card.params.type != '0') {
            return;
        }
        // console.log("点击了文档别地地方，快速编辑应该提交了")

        let domkey = this.getEditFormItemDomkey();
        let className = e.target.className;
        if (this.isOpenBrowser()) { //浏览框点击不提交，阻断冒泡
            return;
        }

        if (this.clickCut()) { // 其他的一些点击阻断，如富文本、明细表新增行内
            return;
        }

        /****
         * //如果domkey存在，那就是点击了当前编辑状态的字段
         * 不存在则点击了编辑外的其他地方
         */
        if (!domkey) {
            if (!className.startsWith("ant-calendar")
                && className != "ant-select-dropdown-menu-item-active ant-select-dropdown-menu-item"
                && className != "ant-select-dropdown-menu-item-active ant-select-dropdown-menu-item text-elli ant-tooltip-open") {
                const _this = this;
                setTimeout(() => {
                    _this.UpdateCardForm();
                }, 200)

            }
        }

    }

    @action //获取可编辑项的domkey
    getEditFormItemDomkey = (e?) => {
        var e = e || window.event;
        var elem = e.target || e.srcElement;
        while (elem) {
            //只有点点到当前编辑的地方才能获取到domkey
            if (elem.className && elem.className.indexOf("cube-card-editformitem2") >= 0) {
                let domkey = elem.getAttribute("data-fieldmark");
                let state = elem.getAttribute("data-fieldattr");
                return state == '1' ? null : domkey;
            }
            elem = elem.parentNode;
        }
        return null;
    }

    @action
    unlockEditFormItem = (bool = false) => {
        // console.log("this.editFieldKey",this.editFieldKey)
        modeForm.changeFieldAttr(this.editFieldKey, 1);
        /***
         * 主表联动主表，输入后直接点击下一个字段编辑，联动有必填影响
         */
        // if(_.isEmpty(this.mainFieldState)){
            // this.setFormItemsCurrentValue({});
        // }
        this.update({ editFieldKey: "", detailDefaultValue: {}, detailkeysState: {}, handletype: '' })
        if (bool) {
            this.setFormItemsCurrentValue({});
            _.forEach(toJS(this.mainFieldState),(state,field)=>{
                this.card.cubeForm.$(field).setViewAttrs("", 3);
            })

            this.oldValue = {};
            _.forEach(this.detalCurrentValue, (value, detail) => {
                _.forEach(value, (item: any, index) => {
                    this.restoreState(detail, item.dtl_index, item);
                })
            })

            this.update({ detalCurrentValue: {}, mainFieldState:{} });
        }
    }

    //浏览按钮对话框是否打开
    isOpenBrowser() {
        var e = e || window.event;
        var elem = e.target || e.srcElement;
        let isTrue = false;
        while (elem) {
            if (elem.className && elem.className.indexOf('mode-card-dialogshow') > -1) { //资源面板的dialog框
                break;
            }
            if (elem.className && (elem.className.startsWith("ant-modal-") || elem.className.startsWith("wea-city-card-container")
                || elem.className.startsWith("ant-select-") || elem.className.startsWith("ant-calendar"))) {
                isTrue = true;
                break;
            }
            elem = elem.parentNode;
        }
        return isTrue;
    }

    clickCut=()=> {
        var e = e || window.event;
        var elem = e.target || e.srcElement;
        let num = 0;
        while (elem) {
            const classnamestr = elem.className;
            if (classnamestr && (classnamestr.indexOf('cube-card-weaRichtext') > -1 ||
                classnamestr.indexOf('detail_data_editing ') > -1 ||
                classnamestr.indexOf('cube-detailbtn-edit') > -1)) {
                return true;
            }
            if(num === 0 && classnamestr&&classnamestr.indexOf('excelDetailTable_wrap') > -1){
                return true;
            }
            elem = elem.parentNode;
            num++;
        }
        return false;
    }

    @action
    UpdateCardForm = () => {
        if (!_.isEmpty(this.detalCurrentValue)) { //明细表新建考虑多行数据校验
            this.checkRequireDetail();
            return;
        }
        /***
         * url或者parm带的参数有的话，
         * 点击编辑直接保存应该带上
         */
        //如果当前控件没有改变，不更新
        if ((!this.editFieldKey || Object.keys(this.formItemsCurrentValue).length <= 0) && _.isEmpty(this.mainFieldState) ) {
            if (this.handelParmUrls()) {
                this.unlockEditFormItem(); //清空值，返回原状态
                return;
            }
        }
        /****
         * 校验必填字段，先判断是不必填
         */
        if (this.check_require()) {
            // console.log(this.editFieldKey, toJS(this.formItemsCurrentValue));
            /**
             * ljc- - 如果单单是修改了明细的某一个字段
             * 考虑行列规则、字段联动处理数据等
             * 该字段是字段联动触发字段,等返回数据后触发提交
             */
            const { inputEntryData } = this.card.cubeTrigger;
            const fieldid = this.editFieldKey.split('_')[0];
            if (inputEntryData && inputEntryData.inputEntry && _.keys(inputEntryData.inputEntry).indexOf(fieldid) > -1) {
                return;
            }
            /*** */
            const { mainFieldState} = this;
            if(!_.isEmpty(mainFieldState)){ //联动主表有必填，先校验主表
                this.checkRequireMain({}, true)
                return;
            }

            
            this.packageMainAndDetail();
        }
    }

    @action
    packageMainAndDetail = () => {
        const values = toJS(this.formItemsCurrentValue);
        const mainparams = {};
        const detailparams = {};
        const { cubeForm } = this.card;
        let template = {};
        const index = this.editFieldKey.split('_')[1];
        _.forEach(values, (val, key) => {
            const { isdetail, detail } = this.card.getFieldProps(key);
            if (isdetail) {
                const detailvalues = cubeForm.$(detail).getValue()[index] || {};
                template = { ...template, [key]: val, dtl_id: detailvalues.dtl_id }
                if (!detailparams.hasOwnProperty(detail)) { detailparams[detail] = [] }
                detailparams[detail] = [template]
            } else {
                mainparams[key] = val;
            }
        });
        const dataRange = _.isEmpty(mainparams) ? 'detail' : (_.isEmpty(detailparams) ? 'main' : 'all');
        this.checkDoQuickSubmit({
            JSONStr: JSON.stringify({ ...mainparams, ...detailparams }),
            dataRange: dataRange
        });
    }

    @action
    checkDoQuickSubmit = (params = {}) => {
        const { layoutBase } = this.card;
        return new Promise((resolve, reject) => {
            if (layoutBase.haveVerifyRepeat && layoutBase.haveVerifyRepeat == '1') { //判断是否有重复验证
                this.card.Actions.submitActions.verifyRepeat(false, toJS(layoutBase.verify_fields), toJS(layoutBase.verify_fieldinfos)).then(() => {
                    this.checkCustomize(params);
                })
            } else {
                this.checkCustomize(params);
            }
        })
    }

    @action
    checkCustomize = (params) => {
        try {
            if (typeof (window.checkCustomize) == 'function') { //全局校验支持异步
                return new Promise((resolve) => {
                    const a: any = window.checkCustomize(resolve);
                    if (typeof a === 'boolean') {
                        resolve(a)
                    }
                }).then(res => {
                    if (res) {
                        this.submitData(params);
                    }
                })
            } else {
                this.submitData(params);
            }
        } catch (e) {
            return false;
        }
    }

    @action
    submitData = (params) => {
        try {
            if (_.isFunction(window.startUploadAll)) {
                window.startUploadAll();
            }
            let allUploaded = false;
            let timer = setInterval(() => {
                allUploaded = true;
                this.card.uploadFields.map((f: string) => {
                    if (!allUploaded) {
                        return;
                    }
                    const { isdetail, detail } = this.card.getFieldProps(f);
                    if (isdetail) {
                        if (this.card.cubeForm.has(detail)) {
                            const detailTable = this.card.cubeForm.$(detail);
                            detailTable.map(row => {
                                if (!allUploaded) {
                                    return;
                                }
                                if (row.has(f)) {
                                    if (!row.$(f).isUpload) {
                                        allUploaded = false;
                                    }
                                }
                            })
                        }
                    } else {
                        if (this.card.cubeForm.has(f)) {
                            if (!this.card.cubeForm.$(f).isUpload) {
                                allUploaded = false;
                            }
                        }
                    }
                })
                if (allUploaded) {
                    if (typeof (getParent()['slideflgfun']) == 'function') {
                        if (getParent()['slideflgfun']()) {
                            getParent()['dosubmitfun']();
                        }
                    }
                    this.doQuickSubmit(params); //快速编辑提交
                    clearInterval(timer);
                }
            }, 100);
        } catch (e) {
            this.doQuickSubmit(params);
        }
    }

    @action
    check_require = () => {
        const viewAttr = this.getEditState(this.editFieldKey);
        const [field, index] = this.editFieldKey.split('_');
        if (viewAttr == '3' && !this.formItemsCurrentValue[field]) {
            //必填校验不通过
            // const field = this.editFieldKey.indexOf('_')>0 ?  :this.editFieldKey;
            const { isdetail, detail } = this.card.getFieldProps(field);
            let errorField;
            if (isdetail) {
                errorField = this.card.cubeForm.$(`${detail}.${index}.${field}`);
                errorField.tips = {
                    visible: true,
                    msg: errorField.errors()
                };
            } else {
                errorField = this.card.cubeForm.$(field);
                errorField.tips = {
                    visible: true,
                    msg: errorField.errors()
                };
            }
            setTimeout(() => {
                errorField.tips = {
                    visible: false,
                    msg: ''
                };
            }, 1500);
            return false;
        }
        return true;
    }

    @action
    checkRequireMain=(mainDatas = {}, bool = false)=>{
        const { mainFieldState, formItemsCurrentValue,card:{cubeForm}} = this;
        let isTrue = true;

        _.forEach(toJS(mainFieldState),(state, field) => {
            if(cubeForm.has(field) &&!cubeForm.$(field).getValue()){
                if(!isTrue ){return }
                isTrue = false;
                const firstErrorField = $(`.cube-card-editformitem2[data-fieldmark=${field}]`);
                scrollTo(firstErrorField, this.card.cubeForm,()=>{
                    let errorField = cubeForm.$(field);
                    errorField.tips = {
                        visible: true,
                        msg: errorField.errors()
                    };
                    setTimeout(() => {
                        errorField.tips = {
                            visible: false,
                            msg: ''
                        };
                    }, 1500);
                });
            }
        });
        if(isTrue && !_.isEmpty(this.detalCurrentValue)){
            this.update({mainFieldState:{}});
            this.checkRequireDetail({}, true);
            return;
        }
        if(isTrue){
            const params = {
                ...formItemsCurrentValue,
            }
            this.checkDoQuickSubmit({
                JSONStr: JSON.stringify(params),
                dataRange: 'main'
            });
        }
    }

    @action
    checkRequireDetail = (detailDatas = {}, bool = false) => {
        const { mainFieldState} = this;
        if(!_.isEmpty(mainFieldState)){ //联动主表有必填，先校验主表
            this.checkRequireMain({}, true)
            return;
        }
        const { detailkeysState, } = this;
        let isTrue = true;
        let isOut = false;
        let detailSubmitValue = {};
        let tempDetailSubValue = {};
        _.forEach(toJS(this.detalCurrentValue), (value: any, detail: string) => {
            const detailTable = this.card.cubeForm.$(detail);
            let detailvalues = detailTable.getValue();
            const tempdatas = value.length == 1 && detailvalues.filter(d => d['dtl_id'] == value[0]['dtl_id'])[0];
            detailvalues =  value.length == 1 ? [{...value[0],...tempdatas,dtl_index:value[0]['dtl_index']}]: detailvalues.filter(d => d['dtl_id'].length > 30);
            detailSubmitValue[detail] = detailvalues;
            tempDetailSubValue[detail] = [];
            _.forEach(value, (item: any) => {
                if (item.dtl_id && detailTable.has(item.dtl_index)) {
                    tempDetailSubValue[detail].push(detailTable.$(item.dtl_index).value)
                }
            })
            let errorField;
            try {
                try {
                    _.forEach(detailkeysState, (state, field) => {
                        const { detail: fieldDetail } = this.card.getFieldProps(field);
                        if (fieldDetail != detail) { return; }
                        for (let i = 0; i < detailvalues.length; i++) {
                            const list = detailvalues[i];
                            if (!list[field]) {
                                if (isOut) { return }
                                isTrue = false; isOut = true;
                                const firstErrorField = $(`.cube-card-editformitem2[data-fieldmark=${field}_${list['dtl_index']}]`);
                                errorField = this.card.cubeForm.$(`${detail}.${list['dtl_index']}.${field}`);
                                scrollTo(firstErrorField, this.card.cubeForm, ($ele) => {
                                    scrollToX(firstErrorField, this.card.cubeForm, () => {
                                        errorField.tips = {
                                            visible: true,
                                            msg: errorField.errors() ? errorField.errors() : errorField.label + getLabel(21423, "未填写")
                                        };
                                    });
                                    setTimeout(() => {
                                        errorField.tips = {
                                            visible: false,
                                            msg: ''
                                        };
                                    }, 1500);
                                });
                                throw new Error('error')
                            }
                        }
                    })
                    if (isOut) {
                        throw new Error('error')
                    }
                } catch (error) {
                    if (error.message != 'error') throw error;
                }

            } catch (error) {
                if (error.message != 'error') throw error;
            }
        })

        if (isTrue) {
            const mainValues: object = {};
            _.forEach(toJS(this.formItemsCurrentValue), (value, field) => {
                const { isdetail } = this.card.getFieldProps(field);
                if (!isdetail) {
                    mainValues[field] = value;
                }
            })
            /**
             * bool =true
             * 字段联动返回后触发校验提交，
             */
            if (bool) {
                detailSubmitValue = tempDetailSubValue;
            }
            const params = {
                ...mainValues,
                ...detailSubmitValue
            }
            this.checkDoQuickSubmit({
                JSONStr: JSON.stringify(params),
                dataRange: _.isEmpty(mainValues) ? 'detail' : 'all'
            });
        }
    }

    /***快速编辑提交 */
    doQuickSubmit = (params = {}) => {
        try {
            const _this = this;
            setTimeout(() => {
                _this.unlockEditFormItem(true);
            }, 100);
            const values = this.formItemsCurrentValue; //表单数据
            if(_.isEmpty(values)){  return    }
            const { layoutBase } = this.card;
            const submitParams = {
                ...this.card.params,
                token: this.card.token,
                layoutid: this.card.layoutid,
                currentLayoutId: this.card.layoutid,
                btntype: '',
                issystemflag: '2',
                oldmodedatastatus: 0,
                isFormMode: '1',
                iscreate: '2',
                src: 'save',
                pageexpandid: layoutBase.pageexpandid,
                isquickedit: '1',
                changeDataTime: this.card.changeDataTime,
                editLayoutid: layoutBase.editLayoutid,
                dataRange: 'all',  //main detail all
                haveInterface: layoutBase.haveInterface,
                JSONStr: JSON.stringify(values),
                ...params
            };
            doSubmit(submitParams).then(action(({ pageExpendResult, quickDetailIds, billid, changeDataTime, needRefresh, errMessage, isChange, status, noRight }) => {
                // console.log("===保存成功了===")
                if (status == '1') {
                    if (noRight) {
                        Modal.info({
                            title: getLabel(15172, '系统提示'),
                            content: getLabel('521919', '数据权限已变更，无法编辑！'),
                            okText: getLabel(382958, "确定"),
                            onOk: () => {
                                window.location.reload();
                            },
                        });
                        return;
                    }
                    message.success(getLabel(83551, '保存成功！'));
                    if (isChange) { //isChange = true 就是没有被改变，不知道咋定义的。。。。
                        if (pageExpendResult) { //接口执行的返回值
                            let obj = JSON.parse(pageExpendResult);
                            if (obj.flag == "false") {
                                Modal.error({ content: obj.errmsg })
                                return;
                            }
                        }
                        /***
                       * 如果页面扩展设置了关联字段，切判断关联字段有变化则需要更新内嵌tab，顶部tab，右键
                       */
                        this.checkAssociatedFields(params, values);
                        /**
                         * 针对明细表设置了合并显示字段的处理
                         */
                        this.checkDetailRowMerge(submitParams.dataRange, submitParams.JSONStr);
                        this.card.update({ changeDataTime, });
                        /**
                         * 是否要刷新页面,这个刷新了整个页面，后面考虑局部刷新替换---ljc
                         * 一般配置的dml等后端接口动作会触发
                         */
                        if (needRefresh) {
                            this.card.reloadCardDatas();
                        }
                        //更新了明细表数据，需要同步更新前端数据
                        this.updateDetailData(quickDetailIds);
                        
                        try {
                            //--------------------------------------是否看板，看板相关处理
                            const { boardid, boardgroup, boardcustomid,viewfrom } = this.card.params;
                            if (boardid && boardgroup && boardcustomid) {
                                if(top.window['current_boardStore']){
                                    top.window['current_boardStore'].cardSaveFun(billid, '0', boardid, boardgroup, boardcustomid);
                                }else if(window.opener && window.opener.cubeStore){
                                    window.opener.cubeStore.boardStore.doSearch();
                                }
                            }else if(viewfrom == 'fromboarditem' && window.opener && window.opener.cubeStore){
                                window.opener.cubeStore.boardStore.doSearch();
                            }else{
                                /***
                                 * 打开的列表数据回调刷新页面-
                                 * excel和相册未注册全局_table方法，加个判断
                                 */
                                this.card.cardTab.disabled = false;
                                // if (window.opener && window.opener._table && window.opener._table.reLoad) {
                                //     window.opener._table.reLoad();
                                // }else if(window.opener && window.opener.cubeStore){
                                //     window.opener.cubeStore.Search.refresh();
                                // }
                                if(window.opener){
                                    const { _table,cubeStore } = window.opener;
                                    if (_table && _table.reLoad) {
                                        let isTreeList = cubeStore && cubeStore.Search.dataShowtype === 'treeType' && cubeStore.Search.changeSearch == '1';// 分组的组合转换，单独判断
                                        if(isTreeList){
                                            cubeStore.Search.refresh();
                                        }else{
                                            _table.reLoad();
                                        }
                                    }else if(cubeStore){
                                        cubeStore.Search.refresh();
                                    }
                                }
                            }
                        } catch (e) {
                        }
                        //----------------------------------------是否看板，看板相关处理
                        /***二维码条形码刷新 */
                        const codeImgFn = this.card.modeExcel.codeImgFn || {};
                        if (submitParams.dataRange != 'detail' && !_.isEmpty(codeImgFn)) {
                            _.forEach(codeImgFn, (fn, key) => {
                                fn();
                            })
                        }
                    } else {
                        this.modalConfirm(errMessage, '');
                    }
                }
            }));
        } catch (error) {

        }
    }

    @action
    checkAssociatedFields = (params: any = {}, values) => {
        let relatedFields: any = [];
        const { layoutBase: { relateField }, reloadParams } = this.card;
        if (_.isEmpty(params)) {
            const mainfields = params.JSONStr && JSON.parse(params.JSONStr) || {};
            relatedFields = _.keys(mainfields).filter(d => d.startsWith('field'));
        } else {
            relatedFields = _.keys(values).filter(d => d.startsWith('field'));
        }
        const intersectionKeys = _.intersection(relateField, relatedFields);
        if (intersectionKeys.length > 0) {
            this.card.cardTab.init({ ...reloadParams, datajson: '' });
        }
    }

    @action
    checkDetailRowMerge = (dataRange: string, formdatas: string) => {
        const { modeExcel, cubeForm } = this.card;
        if (dataRange != 'main') {
            const datas = JSON.parse(formdatas) || {};// { "detail_2": [{ "field42724": "2244", "dtl_id": "78" }] }
            const details = _.reduce(datas, function (result, value, key) {
                if (key.startsWith('detail_')) { result[key] = value; }
                return result;
            }, {});
            _.forEach(details, (value: Array<object>, detail) => {
                const mergeFields = toJS(modeExcel.getExcel(detail).mergeFields) || {};
                const mergeFieldsArr: any = [];
                _.forEach(mergeFields, (v, k) => {
                    if (v && _.isObject(v)) {
                        // @ts-ignore
                        mergeFieldsArr.push('field' + v.fieldid);
                    }
                });
                if (value && value.length > 0) {
                    const changeFields = _.keys(value[0]).filter(d => d.startsWith('field'));
                    const intersectionKeys = _.intersection(mergeFieldsArr, changeFields);
                    if (intersectionKeys.length > 0) {
                        cubeForm.$(detail).forceRender = new Date().getTime();
                    }
                }
            })
        }

    }

    modalConfirm = (errMessage, okText) => {
        Modal.confirm({
            title: errMessage,
            okText: okText || getLabel(354, '刷新'),
            cancelText: getLabel(201, '取消'),
            onOk: () => {
                window.location.reload(); return;
            },
            onCancel: () => { }
        });
    }

    @action
    updateDetailData = (quickDetailIds = {}) => {
        if (quickDetailIds && !_.isEmpty(quickDetailIds)) {
            const { cubeForm } = this.card;
            _.forEach(quickDetailIds, (val: object, key) => {
                if (cubeForm.has(key)) {
                    if (this.handletype == 'copy') {
                        modeForm.checkDetailRow(key, "", true);
                    }
                    const detailvalues = cubeForm.$(key).getValue();
                    const formkeys = cubeForm.$(key).map(d => d.key);
                    _.forEach(detailvalues, (item, index) => {
                        const delid = item.dtl_id || "";
                        if (val.hasOwnProperty(delid)) {
                            cubeForm.$(key).$(formkeys[index]).$('dtl_id').value = val[delid];
                            // field.$(key).$(fieldid).setViewAttrs("", editstate== '2' ? '1':(editstate== '3'?'2':'1'));
                        }
                        if (delid.length > 30) {
                            this.restoreState(key, index, item);
                            this.update({ detalCurrentValue: {}, handletype: '' })
                        }
                    })
                }
            })
        }
    }

    @action
    restoreState = (detail, index, indexValue = {}) => {
        const { cubeForm } = this.card;
        let detailkeys = _.keys(cubeForm.$(detail).$(index).value).filter(d => d.startsWith('field'));
        _.forEach(detailkeys, fieldid => {
            cubeForm.$(detail).$(index).$(fieldid).setViewAttrs("", 3);
        });
    }

    /****
     * 处理行列规则
     *
     */
    doRowColConsFields = () => {
        const { colCals } = this.card.cubeTrigger;
        const colsFields: string[] = [];
        if (toJS(colCals)) {
            _.each(colCals, (toField: string, changeField: string) => {
                colsFields.push(toField);
            });
        }
        return _.uniq(colsFields);
    }

    @action
    handleDetals = (type = '', detail: string, datas: Array<object>) => {
        this.handletype = type;
        const colCons = this.doRowColConsFields();
        const order = detail.split('_')[1];
        const detaildata = {
            [detail]: type === 'delete' ? [] : datas,
            ['deldtlid' + order]: type === 'delete' ? `${_.compact(datas.map(d => _.get(d, `dtl_id`)))}` : ''
        }
        if (colCons.length > 0) {
            const mainValues: object = {};
            const getMainFields = (field) => {
                if (this.formItemsCurrentValue.hasOwnProperty(field)) {
                    mainValues[field] = this.formItemsCurrentValue[field];
                }
            }
            const getMainValues = () => _.forEach(colCons, field => {
                getMainFields(field);
            })
            const _this = this;
            setTimeout(() => {
                getMainValues();
                const params = {
                    ...mainValues,
                    ...detaildata,
                }
                _this.checkDoQuickSubmit({
                    JSONStr: JSON.stringify(params),
                    dataRange: 'all'
                });
            }, 300)
        } else {
            this.checkDoQuickSubmit({
                JSONStr: JSON.stringify(detaildata),
                dataRange: 'detail'
            });
        }

    }

    @action //明细表新增
    addDetals = (detail, index, detailDefaultValue, detailkeysState) => {
        // console.log("detail,index,detailDefaultValue,detailkeys", detail, index, detailDefaultValue, detailkeysState)
        if (!this.detalCurrentValue.hasOwnProperty(detail)) {
            this.detalCurrentValue[detail] = [];
        }
        this.update({ detailkeysState, editFieldKey: detail, handletype: 'add' })
        this.detalCurrentValue[detail].push(detailDefaultValue);
    }

    @action
    recordParms = (data = {}) => {
        const { params } = this.card;
        let fieldkeys = _.keys(params).filter(d => d.startsWith('field'));
        const fieldParams = _.pick(params, fieldkeys);
        this.recordParmurls = { ...fieldParams, ...data };
    }

    @action
    handelParmUrls = () => {
        let isTrue = true;
        if (this.editFieldKey && !_.isEmpty(this.recordParmurls)) {
            const { getFieldProps, cubeForm } = this.card;
            const [field, index] = this.editFieldKey.split('_');
            const { isdetail, detail } = getFieldProps(field);
            if (isdetail) {
                const value = cubeForm.$(detail).$(index).$(field).values();
                if (value == this.recordParmurls[field]) {
                    this.setFormItemsCurrentValue({ [field]: value });
                    isTrue = false;
                }
            } else {
                const value = cubeForm.$(field).values();
                if (value == this.recordParmurls[field]) {
                    this.setFormItemsCurrentValue({ [field]: value });
                    isTrue = false;
                }
            }
        }
        return isTrue;
    }

}
